package utils;

import org.vm.cmbcdirect.utils.DateUtil;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by violorch on 2016/3/22.
 *
 * 用来更改mybatis自动生成的文件的文件名
 */
public class ChangeFilesName {

    private final static String rootPath = "E:\\_violorch\\wechat\\src\\org\\vm\\cmbcdirect\\component";
    private final static String packageName = "org.vm.cmbcdirect.component";
    private final static String oldString = "Mapper";
    private final static String newString = "Dao";

    public static void main(String[] args) throws Exception {
        changeFilesName(new File(rootPath), oldString, newString);
    }

    /**更改文件名
     * @param dir   目标文件夹
     * @param oldString 替换文件内容
     * @param targetString  替换目标
     * **/
    private static void changeFilesName(File dir, String oldString,  String targetString) throws Exception {
        if (!dir.exists()) {
            System.out.println("No this dir.");
            return;
        }
        File[] fs = dir.listFiles();
        for (int i = 0; i < fs.length; i++) {
            String fileName = fs[i].getAbsolutePath();
            if (fileName.contains(oldString)) {
                File oldFile = new File(fileName);
                fileName = fileName.replace(oldString, targetString);
                File newFile = new File(fileName);

                //改名
                oldFile.renameTo(newFile);

                // 更新文件内容
                changeFileContent(newFile, oldString, targetString);

                // 判断是否是Dao类
                if (fileName.endsWith("Dao.java")) {
                    addDaoImplFile(fileName);
                }
            }
            if (fs[i].isDirectory()) {
                try {
                    changeFilesName(fs[i], oldString, targetString);
                } catch (Exception e) {
                }
            }
        }
    }

    // 新增DaoImpl文件
    /**
     #0	E:\_violorch\wechat\src\org\mv\cmbcdirect\dao\FacePersonDao.java
     #1	E:\_violorch\wechat\src\org\mv\cmbcdirect\dao
     #2	cmbcdirect\
     #3	FacePersonDao
     #4	FacePerson
     #5	Dao
     * **/
    private static void addDaoImplFile(String daoName) {
        Pattern pattern = Pattern.compile("((\\w*:*\\\\)*dao)[\\\\](([\\W\\w]*)(Dao))\\.java");
        Matcher m = pattern.matcher(daoName);
        if (!m.matches()) {
            return;
        }
        String parentPath = m.group(1) + "\\impl";
        String targetPath = parentPath + "\\" + m.group(3) + "Impl.java";
        if (TmpBaseUtil.createFile(parentPath, targetPath)) {
            StringBuffer content = new StringBuffer();
            content.append("package " + packageName + ".dao.impl;\n\n");
            content.append("import org.mybatis.spring.SqlSessionTemplate;\n");
            content.append("import org.springframework.beans.factory.annotation.Autowired;\n");
            content.append("import " + packageName + ".dao." + m.group(3) + ";\n");
            content.append("import " + packageName + ".model." + m.group(3).replace("Dao", "") + ";\n\n");
            content.append("/**\n");
            content.append(" * Created by violorch on " + DateUtil.getCurrentDate() + ".\n");
            content.append(" */\n");
            content.append("public class " + m.group(3) + "Impl implements " + m.group(3) + " {\n\n");
            content.append("    @Autowired\n");
            content.append("    private SqlSessionTemplate sqlSessionTemplate;\n\n");

            String modelName = m.group(4).toLowerCase();
            content.append("    public int deleteByPrimaryKey(String " + modelName + "Id" + ") {\n");
            content.append("        return sqlSessionTemplate.delete(\"" + modelName + ".deleteByPrimaryKey\", "
                    + modelName + "Id);\n");
            content.append("    }\n\n");
            content.append("    public int insert(" + m.group(4) + " record) {\n");
            content.append("        return sqlSessionTemplate.insert(\"" + modelName + ".insert\", record);\n");
            content.append("    }\n\n");
            content.append("    public int insertSelective(" + m.group(4) + " record) {\n");
            content.append("        return sqlSessionTemplate.insert(\"" + modelName + ".insertSelective\", record);\n");
            content.append("    }\n\n");
            content.append("    public FacePerson selectByPrimaryKey(String " + modelName + "Id" + ") {\n");
            content.append("        return sqlSessionTemplate.selectOne(\"" + modelName + ".selectByPrimaryKey\", "
                    + modelName + "Id);\n");
            content.append("    }\n\n");
            content.append("    public int updateByPrimaryKeySelective(" + m.group(4) + " record) {\n");
            content.append("        return sqlSessionTemplate.update(\"" + modelName + ".updateByPrimaryKeySelective\", record);\n");
            content.append("    }\n\n");
            content.append("    public int updateByPrimaryKey(" + m.group(4) + " record) {\n");
            content.append("        return sqlSessionTemplate.update(\"" + modelName + ".updateByPrimaryKey\", record);\n");
            content.append("    }\n");
            content.append("}\n");

            write(content.toString(), new File(targetPath));
        }

    }

    // 更新文件内容
    private static void changeFileContent(File targetFile, String oldString, String targetString) {
        String cont = read(targetFile);
        //对得到的内容进行处理
        cont = cont.replaceAll(oldString, targetString);

        //更新源文件
        write(cont, targetFile);
    }

    // 读取文件内容
    public static String read(File src) {
        StringBuffer res = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(src));
            while ((line = reader.readLine()) != null) {
                res.append(line + "\n");
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res.toString();
    }

    // 输出内容到文件
    public static boolean write(String cont, File dist) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(dist));
            writer.write(cont);
            writer.flush();
            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

}
